package com.shop.advice;

import cn.hutool.core.lang.Dict;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import com.shop.dto.PageInfo;
import com.shop.dto.ResponseDto;
import com.shop.local.PageInfoLocal;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * @author wzby
 * @Date: 2022/10/17 17:26
 */
@RestControllerAdvice(basePackages = ResponseAdvice.BASEPACKAGES)
public class ResponseAdvice implements ResponseBodyAdvice<Object> {

    public static final String BASEPACKAGES = "com.shop.controller";


    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
        return true;
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        ResponseDto responseDto = new ResponseDto();
        responseDto.setCode(0);
        responseDto.setMessage("请求成功");

        PageInfo pageInfo = PageInfoLocal.get();
        if (pageInfo != null) {
            Dict dict = Dict.create()
                    .set("total", pageInfo.getTotal())
                    .set("pages", pageInfo.getPages())
                    .set("items", body);
            responseDto.setData(dict);
        } else {
            responseDto.setData(body);
        }

        // 清除
        PageInfoLocal.clean();

        if (selectedConverterType == StringHttpMessageConverter.class) {
            return JSONUtil.toJsonStr(responseDto);
        } else {
            return responseDto;
        }
    }

    @ExceptionHandler
    // 报告异常
    public Object exception(Exception exception) {
        ResponseDto responseDto = new ResponseDto();
        responseDto.setCode(1);
        if (ObjectUtil.isEmpty(exception.getMessage())) {
            responseDto.setMessage(exception.toString());
        } else {
            responseDto.setMessage(exception.getMessage());
        }

        return responseDto;
    }
}

